from datetime import datetime
from openai import OpenAI
from tqsdk.ta import *
import logging

class BybridData:
    dk:pd.DataFrame
    hk:pd.DataFrame
    mk:pd.DataFrame
    m30k:pd.DataFrame
    m15k:pd.DataFrame
    m5k:pd.DataFrame
    
class BybridPosition:
    def __init__(self, key:str,url:str,model:str):
        self.ds = OpenAI(api_key=key, base_url=url)
        self.env_msg=[
            {"role": "system", "content": f"你是一个期货行情分析员，我为您提供行情数据你需要根据数据计算最优持仓比例并以分数的形式返回，注意您只输出-1.0到+1.0的小数代表当前持仓比例，-表示空单，+表示多单，0表示空仓，不要输出其他描述信息"},
            {"role": "system", "content": "最近20日的K线数据DK，最近30小时的K线数据HK，以及当前持仓POSITION"},
            {"role": "system", "content": "30分钟级别：DMA，ATR，BOLL,RSI，KDJ，MACD"}, 
            {"role": "system", "content": "15分钟级别：DMA，ATR，BOLL,RSI，KDJ，MACD"}, 
            {"role": "system", "content": "5分钟级别：ASI，MFI，DFMA，BBI，ATR，CCI，PSY，BOLL，BIAS，RSI，KDJ，MACD"},
            {"role": "system", "content": "1分钟级别：ASI，MFI，DFMA，BBI，ATR，CCI，PSY，BOLL，BIAS，RSI，KDJ，MACD"},
            {"role": "system", "content": "注意你只能通过上面提供的数据不能基于假设做出判断，控制每日交易次数避免频繁交易，控制日内回撤，过滤掉震荡周期"}
        ]
        self.last_msg = None
        self.last_result = .0
        self.model = model
    
    def reasoning_target_position(self,data:BybridData):
        
        #使用ds推理，并根据结果同步持仓
        dks = data.dk[["open", "high", "low", "close","volume"]].iloc[-20:]
        hks = data.hk[["open", "high", "low", "close","volume"]].iloc[-30:]
        
        dma30m = DMA(data.m30k,5,10,20)
        atr30m = ATR(data.m30k,14)
        boll30m = BOLL(data.m30k,26,2)
        rsi30m = RSI(data.m30k,7)
        kdj30m = KDJ(data.m30k,9,3,3)
        macd30m = MACD(data.m30k,12,26,9)

        data30m = pd.concat([data.m30k[["open", "high", "low", "close","volume"]],dma30m, atr30m, boll30m, rsi30m,kdj30m,macd30m], axis=1)

        dma15m = DMA(data.m15k,5,10,20)
        atr15m = ATR(data.m15k,14)
        boll15m = BOLL(data.m15k,26,2)
        rsi15m = RSI(data.m15k,7)
        kdj15m = KDJ(data.m15k,9,3,3)
        macd15m = MACD(data.m15k,12,26,9)
        data15m = pd.concat([data.m15k[["open", "high", "low", "close","volume"]],dma15m, atr15m, boll15m, rsi15m,kdj15m,macd15m], axis=1)

        asi5m = ASI(data.m5k)
        mfi5m = MFI(data.m5k,14)
        #BOLL，
        bbi5m = BBI(data.m5k,3,6,12,24)
        atr5m = ATR(data.m5k,14)
        cci5m = CCI(data.m5k,14)
        psy5m = PSY(data.m5k,12,6)
        boll5m = BOLL(data.m5k,26,2)
        #BIAS，WR，RSI，KDJ，MACD
        bias5m = BIAS(data.m5k,6)
        #wr = WR(mk.close,mk.high,mk.low)[-60:]
        rsi5m = RSI(data.m5k,7)
        kdj5m = KDJ(data.m5k,9,3,3)
        macd5m = MACD(data.m5k,12,26,9)

        data5m = pd.concat([data.m5k[["open", "high", "low", "close","volume"]],asi5m, mfi5m, bbi5m, atr5m,cci5m,psy5m,boll5m,bias5m,rsi5m,kdj5m,macd5m], axis=1)

        asi1m = ASI(data.mk)
        mfi1m = MFI(data.mk,14)
        #BOLL，
        bbi1m = BBI(data.mk,3,6,12,24)
        atr1m = ATR(data.mk,14)
        cci1m = CCI(data.mk,14)
        psy1m = PSY(data.mk,12,6)
        boll1m = BOLL(data.mk,26,2)
        #BIAS，WR，RSI，KDJ，MACD
        bias1m = BIAS(data.mk,6)
        #wr = WR(mk.close,mk.high,mk.low)[-60:]
        rsi1m = RSI(data.mk,7)
        kdj1m = KDJ(data.mk,9,3,3)
        macd1m = MACD(data.mk,12,26,9)

        data1m = pd.concat([data.mk[["open", "high", "low", "close","volume"]],asi1m, mfi1m, bbi1m, atr1m,cci1m,psy1m,boll1m,bias1m,rsi1m,kdj1m,macd1m], axis=1)

        req_msg = self.env_msg.copy()
        if self.last_msg is not None:
            req_msg.append({'role': 'user', 'content': self.last_msg})
        if self.last_result is not None:
            req_msg.append({'role': 'assistant', 'content': self.last_result})
        

        self.last_msg = (
            f"DK (last 20 days)：\n{dks.round(0).astype(int)}\n\n"
            f"HK (last 30 hours)：\n{hks.round(0).astype(int)}\n\n"
            f"POSITION：\n{self.last_result}\n\n"
            f"30分钟周期数据(last 20)：\n{data30m.iloc[-20:].round(0).astype(int)}\n\n"
            f"15分钟周期数据(last 20)：\n{data15m.iloc[-20:].round(0).astype(int)}\n\n"
            f"5分钟周期数据(last 24)：\n{data5m.iloc[-24:].round(0).astype(int)}\n\n"
            f"1分钟周期数据(last 30)：\n{data1m.iloc[-30:].round(0).astype(int)}\n\n"
        ) 
        #print(self.last_msg)
        req_msg.append({'role': 'user', 'content': self.last_msg})
        try:
            response = self.ds.chat.completions.create(
                model=self.model,
                #model="deepseek-r1:32b",
                messages=req_msg,
                stream=False
            )
            print(response.choices[0].message.content)
            self.last_result = float(response.choices[0].message.content.strip())
            logging.info(f"{datetime.now()}:position-> {self.last_result} reasoning_content:{response.choices[0].message.reasoning_content}")
        except Exception as e:
            print("Error:", e)
        return self.last_result

    
    
        